package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"shop/cache"
	"shop/pkg"
	"strconv"
	"time"

	"shop/shopRpc/internal/svc"
	"shop/shopRpc/shopRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *shopRpc.SendSmsRequest) (*shopRpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	limitKey := "LIMIT:" + in.Mobile
	count, _ := cache.Rdb.Get(l.ctx, limitKey).Int()
	if count > 0 {
		return nil, errors.New("一分钟只能发送一次")
	}

	code := rand.Intn(9000) + 1000
	if !pkg.Send(in.Mobile, strconv.Itoa(code)) {
		return nil, errors.New("短信发送失败")
	}

	key := fmt.Sprintf("SMS:%s", in.Mobile)
	err := cache.Rdb.Set(l.ctx, key, code, time.Minute*1).Err()
	if err != nil {
		return nil, errors.New("短信发送异常")
	}

	cache.Rdb.Incr(l.ctx, limitKey)
	cache.Rdb.Expire(l.ctx, limitKey, time.Minute*1)

	return &shopRpc.SendSmsResponse{
		Success: true,
	}, nil
}
